/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

import UTIL.DatabaseConnector;
import UTIL.InputValidator;
import UTIL.TableManager;
import datechooser.beans.DateChooserCombo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.JDialog;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 *
 * @author Belthazod
 */
public class WarrantyController {
    DatabaseConnector dbConnector = DatabaseConnector.getInstance();
    TableManager warrantyTableManager;
    TableManager selectItemTableManager;
    JTextField receiptNumberInput;
    JLabel productNameLabel;
    JLabel durationLabel;
    JLabel salesDateLabel;
    JLabel salesIDLabel;
    JLabel productIDLabel;
    JLabel receiptNumberLabel;
    JLabel serialNumberLabel;
    JDialog changeWarrantyDialog;
    JLabel salesIDSelectLabel;
    JLabel receiptNumberSelectLabel;
    JLabel salesDateSelectLabel;
    JLabel ProductName;
    JLabel SalesDate;
    JLabel ReceiptNo;
    JLabel Valid;
    JLabel  SerialNo;
    JLabel Date;
    DateChooserCombo dateChooser;
    JButton acceptButton;
    DateChooserCombo dateReturnedDateChooser;
    JTextField newSerialNumberInput;
    JDialog newSerialNumberDialog;
    public WarrantyController(JTable warrantyTable, JTextField serialNumberInput, 
            JLabel productNameLabel, JLabel durationLabel, 
            JLabel salesDateLabel, JLabel salesIDLabel, 
            JLabel productIDLabel, JLabel receiptNumberLabel, 
            JLabel serialNumberLabel, JDialog changeWarrantyDialog, 
            JTable selectItemTable, JLabel salesIDSelectLabel, 
            JLabel receiptNumberSelectLabel, JLabel salesDateSelectLabel, 
            DateChooserCombo dateReturnedDateChooser, JDialog newSerialNumberDialog, 
            JTextField newSerialNumberInput, JLabel ProductName,
            JLabel SalesDate, JLabel ReceiptNo,
            JLabel Valid, JLabel SerialNo,
            JLabel Date, DateChooserCombo dateChooser, JButton acceptButton){
        this.productNameLabel = productNameLabel;
        this.durationLabel = durationLabel;
        this.salesDateLabel = salesDateLabel;
        this.receiptNumberInput = serialNumberInput;
        this.salesIDLabel = salesIDLabel;
        this.productIDLabel = productIDLabel;
        warrantyTableManager = new TableManager(warrantyTable);
        this.receiptNumberLabel = receiptNumberLabel;
        this.serialNumberLabel = serialNumberLabel;
        this.changeWarrantyDialog = changeWarrantyDialog;
        this.selectItemTableManager = new TableManager(selectItemTable);
        this.salesIDSelectLabel = salesIDSelectLabel;
        this.receiptNumberSelectLabel = receiptNumberSelectLabel;
        this.salesDateSelectLabel = salesDateSelectLabel;
        this.dateReturnedDateChooser = dateReturnedDateChooser;
        this.newSerialNumberDialog = newSerialNumberDialog;
        this.newSerialNumberInput = newSerialNumberInput;
        this.changeWarrantyDialog = changeWarrantyDialog;
        this.ProductName = ProductName;
        this.SalesDate = SalesDate;
        this.ReceiptNo = ReceiptNo;
        this.Valid = Valid;
        this.SerialNo = SerialNo;
        this.Date = Date;
        this.dateChooser = dateChooser;
        this.acceptButton = acceptButton;
        
        selectItemTableManager.hideColumn(0);
        this.newSerialNumberDialog.setLocationRelativeTo(null);
        this.changeWarrantyDialog.setLocationRelativeTo(null);
    }
    
    public void searchReceiptNumber(){
        try{
            DateFormat dffrom = new SimpleDateFormat("MMMMM d, yyyy");
            DateFormat dfto = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf = new SimpleDateFormat("MMMMM d, yyyy");
            String receiptNumberValue = receiptNumberInput.getText();
            int warrantyItemsCount = 0;
            System.out.print(receiptNumberValue);
            ResultSet rs = dbConnector.query("SELECT name, sales_date, sales_details.warranty_duration, sales_details.sales_id, sales_details.product_ID, receipt_number, serial_number FROM sales_details JOIN product USING(product_id) JOIN sales USING(sales_id) WHERE sales.receipt_number = ?", receiptNumberValue);
            while(rs.next()){
                String serialNumber = rs.getString(7);
                if(serialNumber!=null ){
                    warrantyItemsCount++;
                }
            }
            rs.last();
            System.out.println("Warranty count"+ warrantyItemsCount);
            System.out.println("Row count"+ rs.getRow());
            
            if(warrantyItemsCount == 1){
                ProductName.setVisible(true);
                SalesDate.setVisible(true);
                ReceiptNo.setVisible(true);
                Valid.setVisible(true);
                SerialNo.setVisible(true);
                Date.setVisible(true);
                dateChooser.setVisible(true);
                acceptButton.setVisible(true);
                rs.beforeFirst();
                while(rs.next()){
                    String productName = rs.getString(1);
                    String salesDate = rs.getString(2).substring(0,10);
                    int duration = rs.getInt(3);
                    String salesID = rs.getString(4);
                    String productID = rs.getString(5);
                    String receiptNumber = rs.getString(6);
                    String serialNumber = rs.getString(7);

                    if(duration > 0){
                ProductName.setVisible(true);
                SalesDate.setVisible(true);
                ReceiptNo.setVisible(true);
                Valid.setVisible(true);
                SerialNo.setVisible(true);
                Date.setVisible(true);
                dateChooser.setVisible(true);
                acceptButton.setVisible(true);
                        Date date = dfto.parse(salesDate);
                        String dateOfSale = sdf.format(date);
                        productNameLabel.setText(productName);
                        salesDateLabel.setText(dateOfSale);
                        durationLabel.setText(duration + "month(s)");
                        salesIDLabel.setText(salesID);
                        productIDLabel.setText(productID);
                        receiptNumberLabel.setText(receiptNumber);
                        serialNumberLabel.setText(serialNumber);
                    }
                }
            }else if(warrantyItemsCount > 1){
                
                rs.beforeFirst();
                selectItemTableManager.clearTableContents();
                while(rs.next()){
                    String productName = rs.getString(1);
                    String salesDate = rs.getString(2).substring(0,10);
                    String duration = rs.getString(3);
                    String salesID = rs.getString(4);
                    String productID = rs.getString(5);
                    String receiptNumber = rs.getString(6);
                    String serialNumber = rs.getString(7);
                    
                    Date date = dfto.parse(salesDate);
                    String dateOfSale = sdf.format(date);
                    receiptNumberSelectLabel.setText(receiptNumber);
                    salesDateSelectLabel.setText(dateOfSale);
                    salesIDSelectLabel.setText(salesID);
                    
                    
                    if(serialNumber != null){
                        selectItemTableManager.addRowContent(new String[]{productID, productName, serialNumber, duration+" month(s)"});
                    }
                }
                changeWarrantyDialog.setVisible(true);
            }else if(rs.getRow() > 0 && warrantyItemsCount == 0){
                JOptionPane.showMessageDialog(null, "The receipt with the receipt number you have entered does not contain any items covered by warranty.\nPlease enter an existing receipt number with items with warranty and click 'Search'", "No items with warranty", JOptionPane.ERROR_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(null, "No transaction with that receipt number was found. Please enter an existing receipt number and click 'Search'.", "Receipt Not found", JOptionPane.ERROR_MESSAGE);
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }catch(ParseException pe){
            pe.printStackTrace();
        }
    }
    

    public void updateWarrantyTable(){
        try{
            ResultSet rs = dbConnector.query("SELECT warranty_id, name, old_serial_number, new_serial_number, warranty_ret_date, old_item_status FROM warranty JOIN Product USING(product_id) ");
            warrantyTableManager.clearTableContents();
            while(rs.next()){
                String warrantyID = rs.getString(1);
                String name = rs.getString(2);
                String oldSerialNumber = rs.getString(3);
                String newSerialNumber = rs.getString(4);
                String returnDate = rs.getString(5);
                String oldItemStatus = rs.getString(6);

                warrantyTableManager.addRowContent(new String[]{warrantyID, returnDate, name, oldSerialNumber, newSerialNumber, oldItemStatus});
            }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }
    }
    
    public void acceptItemAsCovered(){
        try{
            int result = JOptionPane.showConfirmDialog(null, "Are you sure this is the correct item being returned?", "Confirm transaction", JOptionPane.YES_NO_OPTION);
            if(result == 0){
                String salesID = salesIDLabel.getText();
                String productID = productIDLabel.getText();
                String oldSerialNumber = serialNumberLabel.getText();
                String dateInput = dateReturnedDateChooser.getText().split(",")[1].substring(1).concat(","+ dateReturnedDateChooser.getText().split(",")[2]);
                String newSerialNumber  = newSerialNumberInput.getText();
                DateFormat dffrom = new SimpleDateFormat("MMMMM d, yyyy");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

                Date date = dffrom.parse(dateInput);
                String warrantyReturnDate = sdf.format(date);
                ResultSet rs = dbConnector.query("SELECT supplier_id FROM product WHERE product_id = ?", productID);
                rs.next();
                String supplierID = rs.getString(1);
                dbConnector.insert("INSERT INTO warranty (sales_id, product_id, warranty_ret_date, old_serial_number, new_serial_number, w_supplier) VALUES(?,?,?,?,?,?)", 
                            new String[]{salesID, productID, warrantyReturnDate, oldSerialNumber, newSerialNumber, supplierID });
                
                dbConnector.update("UPDATE sales_details SET serial_number = ? WHERE sales_id = ?  AND product_id = ? AND serial_number = ?", new String[]{newSerialNumber, salesID, productID},  oldSerialNumber );
             
                updateWarrantyTable();
                InputValidator.clearInput(new JLabel[]{receiptNumberLabel, serialNumberLabel, productIDLabel, salesIDLabel, durationLabel, salesDateLabel, receiptNumberLabel, productNameLabel});
                ProductName.setVisible(false);
                SalesDate.setVisible(false);
                ReceiptNo.setVisible(false);
                Valid.setVisible(false);
                SerialNo.setVisible(false);
                Date.setVisible(false);
                dateChooser.setVisible(false);
                acceptButton.setVisible(false);
                newSerialNumberDialog.dispose();
            }
        }catch(NullPointerException npe){
            npe.printStackTrace();
            JOptionPane.showMessageDialog(null, "No item is being accepted.", "Input Error", JOptionPane.ERROR_MESSAGE);
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }catch(ParseException pe){
            pe.printStackTrace();
        }
    }
    
    public void selectWarrantyItemFromList(){
        ProductName.setVisible(true);
                SalesDate.setVisible(true);
                ReceiptNo.setVisible(true);
                Valid.setVisible(true);
                SerialNo.setVisible(true);
                Date.setVisible(true);
                dateChooser.setVisible(true);
                acceptButton.setVisible(true);
                
        productNameLabel.setText(selectItemTableManager.getValueAt(selectItemTableManager.getSelectedRow(), 1));
        durationLabel.setText(selectItemTableManager.getValueAt(selectItemTableManager.getSelectedRow(), 3));
        salesDateLabel.setText(salesDateSelectLabel.getText());
        salesIDLabel.setText(salesIDSelectLabel.getText());
        productIDLabel.setText(selectItemTableManager.getValueAt(selectItemTableManager.getSelectedRow(), 0));
        receiptNumberLabel.setText(receiptNumberSelectLabel.getText());
        serialNumberLabel.setText(selectItemTableManager.getValueAt(selectItemTableManager.getSelectedRow(), 2));
        
        changeWarrantyDialog.dispose();
    }
    
    public void returnToSupplier(){
        String warrantyID = warrantyTableManager.getIDFromTable(warrantyTableManager.getSelectedRow());
        String productName = warrantyTableManager.getValueAt(warrantyTableManager.getSelectedRow(),2);
        String serialNumber = warrantyTableManager.getValueAt(warrantyTableManager.getSelectedRow(),3);
        try{
            int result = JOptionPane.showConfirmDialog(null, "This would mark the product "+ productName +" with serial number " + serialNumber + " as returned to supplier. \n\nContinue?", "Confirm return to supplier", JOptionPane.YES_NO_OPTION);
            if(result == 0){
                dbConnector.update("UPDATE warranty SET old_item_status = ? WHERE warranty_id = ?", new String[]{"returned"} , warrantyID);
                updateWarrantyTable();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    
}
